package com.moore.Servlet;

import com.moore.model.User;
import com.moore.net.HttpRequest;
import com.moore.net.HttpResponse;
import com.moore.net.HttpServlet;
import com.moore.utils.UserUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;

public class RegServlet extends HttpServlet{

    @Override
    public byte[] doGet(HttpRequest request, HttpResponse response) {
        String responseData;
        Random random = new Random();
        int id = random.nextInt(100);
        // 获取请求的数据
        String account = request.getParams().get("account");
        String password = request.getParams().get("password");
        String nickName = null;
        try {
            nickName = URLDecoder.decode(request.getParams().get("nickName"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        String avatar = request.getParams().get("avatar");
        // 检测账号是否存在，若否则添加用户
        if (UserUtils.getUser(account, password) != null) {
            responseData = "exist";
        } else {
            String type;
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String time = now.format(formatter);
            try {
                type = UserUtils.insertUser(new User(id,account,password,nickName,
                        URLDecoder.decode(avatar, "UTF-8"),0,0,
                        0, time, time));
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
            if (type.equals("success")){
                responseData = "success";
            } else {
                responseData = "fail";
            }
        }
        return responseData.getBytes(StandardCharsets.UTF_8);
    }
}
